#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

namespace dict_ns
{
    const std::string gdefaultpath = "./dict.txt";
    const std::string sep = ": ";
    // 业务模块
    class Dict
    {
    private:
        bool load()
        {
            std::ifstream in(_dict_conf_filepath);
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error\n", _dict_conf_filepath.c_str());
                return false;
            }
            std::string message;
            while (std::getline(in, message))
            {
                if (message.empty())
                    continue;
                auto pos = message.find(sep);
                if (pos == std::string::npos)
                    continue;
                std::string word = message.substr(0, pos);
                if (word.empty())
                    continue;
                std::string han = message.substr(pos + sep.size());
                if (han.empty())
                    continue;
                _dict[word] = han;
                LOG(DEBUG, "load info %s:%s\n", word.c_str(), han.c_str());
            }
            in.close();
            LOG(DEBUG, "load %s success\n", _dict_conf_filepath.c_str());
            return true;
        }

    public:
        Dict(const std::string &dict_conf_filepath = gdefaultpath)
            : _dict_conf_filepath(dict_conf_filepath)
        {
            load();
        }
        std::string translate(const std::string &word, bool &ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if (iter == _dict.end())
            {
                ok = false;
                return "未找到";
            }
            return _dict[word];
        }
        ~Dict()
        {
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_conf_filepath;
    };
}
